package xyz.guhong.play;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import xyz.guhong.play.core.DataLocationCore;
import xyz.guhong.play.entity.Area;
import xyz.guhong.play.entity.City;
import xyz.guhong.play.entity.Province;
import xyz.guhong.play.mapper.AreaMapper;
import xyz.guhong.play.mapper.CityMapper;
import xyz.guhong.play.mapper.ProvinceMapper;

import java.util.Set;

/**
 * 将行政区划存入mysql
 * 使用前设置好数据库连接信息。
 * 并且初始化表结构，在sql目录下执行structure.sql可以快速创建数据表结构
 * 当然你也可以直接执行data_location.sql文件，里面是已经生成好的结构和数据
 *
 * 如果数据库和我这里的实体类不一样，那就要自己改实体类
 *
 * @author 李双凯
 */
public class SaveToMySQL {

    private static ApplicationContext spring = new ClassPathXmlApplicationContext("applicationContext.xml");

    private static ProvinceMapper provinceMapper = spring.getBean(ProvinceMapper.class);

    private static CityMapper cityMapper = spring.getBean(CityMapper.class);

    private static AreaMapper areaMapper = spring.getBean(AreaMapper.class);

    public static void main(String[] args) {
        DataLocationCore.start();
        final Set<Province> provinceSet = DataLocationCore.getProvinceSet();
        final Set<City> citySet = DataLocationCore.getCitySet();
        final Set<Area> areaSet = DataLocationCore.getAreaSet();
        System.out.println("开始插入mysql数据库");

        try{
            for (Province province : provinceSet) {
                provinceMapper.insert(province);
            }
            System.out.println("省份插入完成");
        } catch (Exception e){
            System.out.println("插入省份出错"+e.getMessage());
            e.printStackTrace();
        }
        try{
            for (City city : citySet) {
                cityMapper.insert(city);
            }
            System.out.println("省份市区完成");
        } catch (Exception e){
            System.out.println("插入市区出错"+e.getMessage());
            e.printStackTrace();
        }
        try{
            for (Area area : areaSet) {
                areaMapper.insert(area);
            }
            System.out.println("县城插入完成");
        } catch (Exception e){
            System.out.println("插入县城出错"+e.getMessage());
            e.printStackTrace();
        }
       System.out.println("程序结束");
    }
}
